package com.erli.exchange.core.util;

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.Source;
import javax.xml.transform.sax.SAXSource;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

/**
 * JAXB实现JAVA对象和XML字符串的互相转换
 * 
 * @author lihu
 * @create 2017年9月20日 下午2:24:45
 */
public class JAXBUtil {

	private JAXBUtil() {
	}

	/**
	 * 将JAVA对象转换为XML
	 * 
	 * @param obj
	 * @return
	 * @author lihu
	 * @throws JAXBException
	 * @throws IOException
	 * @create 2017年9月20日 下午2:30:00
	 */
	public static String toXML(final Object obj) throws JAXBException, IOException {
		final StringWriter stringWriter = new StringWriter();
		final JAXBContext context = JAXBContext.newInstance(obj.getClass());
		final Marshaller marshaller = context.createMarshaller();
		// 格式化xml输出的格式
		marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
		marshaller.marshal(obj, stringWriter);
		final String xml = stringWriter.toString();
		stringWriter.close();
		return xml;
	}

	/**
	 * 将XML转换为JAVA对象
	 * 
	 * @param clazz
	 * @param xml
	 * @return
	 * @author lihu
	 * @throws JAXBException
	 * @create 2017年9月20日 下午2:30:28
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static <T> T fromXML(final Class clazz, final String xml) throws Exception {
		final JAXBContext context = JAXBContext.newInstance(clazz);
		final Unmarshaller unmarshaller = context.createUnmarshaller();
		final StringReader reader = new StringReader(xml);
		// 忽略命名空间的解析xml
		final SAXParserFactory sax = SAXParserFactory.newInstance();
		sax.setNamespaceAware(false);
		final XMLReader xmlReader = sax.newSAXParser().getXMLReader();
		final Source source = new SAXSource(xmlReader, new InputSource(reader));
		final Object object = unmarshaller.unmarshal(source);
		return (T) clazz.cast(object);
	}

}
